package com.zl.tby.core.interceptor;

import com.zl.tby.core.common.R;
import com.zl.tby.core.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;
import org.noear.solon.validation.ValidatorException;
@Slf4j
@Component
public class GlobalResultInterceptor implements RouterInterceptor {
    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        //提示：这里和 doFilter 差不多...
        try {
            chain.doIntercept(ctx, mainHandler);
            if (!ctx.getHandled()) {
                ctx.status(404);
            }
        } catch (ValidatorException | GlobalException ex) {
            ctx.render(R.failed(ex.getMessage()));
        } catch (Throwable ex) {
            ctx.render(R.failed("服务器内部错误: " + ex.getMessage()));
            log.error("服务器内部错误: ", ex);
        }
    }
}
